package com.huajx.hanvon;

import java.util.logging.Logger;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;

import com.huajx.http.kit.HttpKit;

import Com.FirstSolver.Splash.FaceId_Item;

public class HanvonServerHandler extends IoHandlerAdapter {
	private Logger logger = Logger.getLogger(this.getClass().getName());
	// 序列号属性键
	private static final AttributeKey KEY_SERIALNUMBER = new AttributeKey(HanvonServerHandler.class, "SerialNumber");
	
	private String schoolId;
	private String schoolName;
	
	private boolean isPhoto = false;
	
	private String serverUrl="http://localhost:8080/jxt-weixin";
	
	private void printMessage(Object message) {
		logger.info(message.toString());
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.warning("服务器启动发生异常 : " + cause.getMessage());
		
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		// 显示消息内容
		String answer = message.toString();
		
		if (answer.startsWith("PostRecord")) {
			// 获取设备序列号
			String SerialNumber = FaceId_Item.GetKeyValue(answer, "sn");
			session.setAttribute(KEY_SERIALNUMBER, SerialNumber);
			
			// 服务器回应
			if (isPhoto) {
				session.write("Return(result=\"success\" postphoto=\"true\")");
			} else {
				session.write("Return(result=\"success\" postphoto=\"false\")");
			}
		} else if (answer.startsWith("Record")) {
			// 获取设备序列号
			String SerialNumber =
			 session.getAttribute(KEY_SERIALNUMBER).toString();
			
			// 处理卡点数据
			HttpKit.post(serverUrl + "/a/hanvon", message.toString(), schoolId, schoolName,SerialNumber);
			// 服务器回应
			session.write("Return(result=\"success\")");
		} else if (answer.startsWith("PostEmployee")) {
			// 准备上传人员信息

			// 服务器回应
			session.write("Return(result=\"success\")");
		} else if (answer.startsWith("Employee")) {
			// 读取人员信息

			// 服务器回应
			session.write("Return(result=\"success\")");
		} else if (answer.startsWith("GetRequest")) {
			// 处理命令下发
//			String Command = textAreaDeviceCommand.getText();
//			if (!Utils.IsNullOrEmpty(Command)) {
//				session.write(Command);
////				textAreaDeviceCommand.clear();
//			}
		} else if (answer.startsWith("Quit")) {
			// 结束会话
			session.closeNow();
		}
	}
}
